﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Data;

namespace SStuff.FlowControls
{
    /// <summary>
    /// Control usable inside an itemtemplate of a FlowItemsControl2D or 3D exposing selection / mouse states
    /// </summary>
    [TemplateVisualState(GroupName = "SelectionStates", Name = "Selected")]
    [TemplateVisualState(GroupName = "SelectionStates", Name = "Unselected")]
    [TemplateVisualState(GroupName = "MouseStates", Name = "MouseOver")]
    [TemplateVisualState(GroupName = "MouseStates", Name = "MouseOut")]
    public class InFlowContentControl : ContentControl
    {
        bool _loaded;
        /// <summary>
        /// Find the FlowItem ancestor
        /// </summary>
        /// <returns></returns>
        FlowItemBase FindFlowItem()
        {
            var candidate = VisualTreeHelper.GetParent(this);
            while (candidate != null)
            {
                var flowItem = candidate as FlowItemBase;
                if (flowItem!=null)
                    return flowItem;
                candidate = VisualTreeHelper.GetParent(candidate);
            }
            return null;
        }

        /// <summary>
        /// Create an instance of InFlowContentControl
        /// </summary>
        public InFlowContentControl()
        {
            DefaultStyleKey = typeof(InFlowContentControl);

            Binding selectionBinding = null;

            Loaded+=(s,a) =>
                {
                    _loaded = true;
                    var flowItem = FindFlowItem();
                    if (flowItem != null)
                    {
                        //selectionBinding = new Binding() { Source = flowItem, Path = new PropertyPath("IsSelected") };
                        //SetBinding(IsSelectedProperty, selectionBinding);                      
                    }
                    UpdateSelectedVisualState();
                };

//            #if PHONE
//            LayoutUpdated += (s, a) =>
//                {
//                    if (!this.IsInMainVisualTree())
//                    {
//                        if (_loaded)
//                        {
//                            _loaded = false;
//                            if (selectionBinding != null)
//                            {
//                                ClearValue(IsSelectedProperty);
//                                selectionBinding = null;
//                            }
//                        }
//                    }
//                    else
//                    {
//                        if (!_loaded)
//                        {
//                            _loaded = true;
//                            var flowItem = FindFlowItem();
//                            if (flowItem != null)
//                            {
//                                //selectionBinding = new Binding() { Source = flowItem, Path = new PropertyPath("IsSelected") };
//                                //SetBinding(IsSelectedProperty, selectionBinding);                      
//                            }
//                            UpdateSelectedVisualState();
//                        }
//                    }
//                };
//#else
            Unloaded+=(s,a) =>
                {
                    _loaded = false;
                    if (selectionBinding != null)
                    {
                        ClearValue(IsSelectedProperty);
                        selectionBinding = null;
                    }

                };
//#endif

        }

        /// <summary>
        /// Change the mouse visual state
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseEnter(MouseEventArgs e)
        {
            base.OnMouseEnter(e);
            if(this.IsInMainVisualTree())
                VisualStateManager.GoToState(this, "MouseOver", true);
        }


        /// <summary>
        /// Change the mouse visual state
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseLeave(MouseEventArgs e)
        {
            base.OnMouseLeave(e);
            if (this.IsInMainVisualTree())
                VisualStateManager.GoToState(this, "MouseOut", true);            
        }

        /// <summary>
        /// Update the Selected visual state
        /// </summary>
        private void UpdateSelectedVisualState()
        {

            if (this.IsInMainVisualTree())
                VisualStateManager.GoToState(this, IsSelected ? "Selected" : "Unselected", _loaded);
        }

        /// <summary>
        /// Get or set the heading background
        /// </summary>
        public Brush HeadingBackground
        {
            get { return (Brush)GetValue(HeadingBackgroundProperty); }
            set { SetValue(HeadingBackgroundProperty, value); }
        }

        // Using a DependencyProperty as the backing store for HeadingBackground.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty HeadingBackgroundProperty =
            DependencyProperty.Register("HeadingBackground", typeof(Brush), typeof(InFlowContentControl), new PropertyMetadata(null));


        /// <summary>
        /// Get or set the heading
        /// </summary>
        public object Heading
        {
            get { return GetValue(HeadingProperty); }
            set { SetValue(HeadingProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Heading.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty HeadingProperty =
            DependencyProperty.Register("Heading", typeof(object), typeof(InFlowContentControl), new PropertyMetadata(null));


        /// <summary>
        /// Get or set the heading template
        /// </summary>
        public DataTemplate HeadingTemplate
        {
            get { return (DataTemplate)GetValue(HeadingTemplateProperty); }
            set { SetValue(HeadingTemplateProperty, value); }
        }

        // Using a DependencyProperty as the backing store for HeadingTemplate.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty HeadingTemplateProperty =
            DependencyProperty.Register("HeadingTemplate", typeof(DataTemplate), typeof(InFlowContentControl), new PropertyMetadata(null));




        /// <summary>
        /// Get or set the Selected state
        /// </summary>
        public bool IsSelected
        {
            get { return (bool)GetValue(IsSelectedProperty); }
            set { SetValue(IsSelectedProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsSelected.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsSelectedProperty =
            DependencyProperty.Register("IsSelected", typeof(bool), typeof(InFlowContentControl), new PropertyMetadata(false,
                (s, a) => ((InFlowContentControl) s).UpdateSelectedVisualState()));




    }
}
